import asyncio
from lib.config.index import sensor_config
from lib.sensors.oled import ops

oled = None
width = None

__service__ = "oled_show_ip"
__description__ = "oled show device ip"


def oled_display_ip(ip_str):
    global oled, width
    x = 0
    y = 0
    oled.fill(0)
    lines = ip_str.split(".")
    for i in range(0, len(lines), 2):
        first = lines[i]
        if i > 0:
            first = "." + first
        second = "." + lines[i + 1]

        # place center
        x = int((width - (len(first) + len(second)) * 8) / 2)
        oled.text(first, x, y)
        x += len(first) * 8
        oled.text(second, x, y)
        y += 12
        x = 0

    oled.show()


def init():
    global oled, width
    oled_config = sensor_config.get_sensor("ssd1306")

    if oled_config:
        scl = oled_config["scl"]
        sda = oled_config["sda"]
        width = oled_config["width"]
        height = oled_config["height"]
        oled = ops.init_oled(scl, sda, width, height)


async def run():
    from utils import device

    while True:
        if not oled:
            continue

        ip = device.info["ifconfig"]["ip"]
        oled_display_ip(ip)
        await asyncio.sleep(30)


if __name__ == "__main__":
    from utils import device

    init()
    oled.fill(0)
    ip = "192.168.114.105"
    oled_display_ip(ip)
